package cc.sheji.service;


import cc.sheji.domain.Job;
import cc.sheji.domain.Notice;
import cc.sheji.reposity.JobRepository;
import cc.sheji.reposity.NoticeRepository;
import cc.sheji.util.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AsynService {

    @Autowired
    HttpUtil httpUtil;
    @Autowired
    JobRepository jobRepository;

    @Value("${updataPath}")
    String updataPath;

    @Value("${uploadUrl}")
    String uploadUrl;
    @Autowired
    NoticeRepository noticeRepository;

    @Async("getAsyncExecutor")
    public void download(Job job) throws Exception {

        if (job == null)
            return;
        try {
            job.setState(3);
            jobRepository.save(job);
            List<String> imageList = new ArrayList<>();
            JSONArray resultImages = job.getResultImages();
            long executionTime =0; // 计算执行时间（单位为毫秒）
            for (int i = 0; i < resultImages.size(); i++) {
                long start = System.currentTimeMillis(); // 记录开始时间
                try {
                    String imageUrl = resultImages.getString(i);
                    if(imageUrl==null||imageUrl.length()<5){
                        continue;
                    }
                    System.out.println("开始下载图片 " + imageUrl);
                    String filePath = httpUtil.downloadImage(imageUrl, updataPath);

                    if(filePath==null){
                        Thread.sleep(1000);
                        filePath = httpUtil.downloadImage(imageUrl, updataPath);

                    }

                    if(filePath==null||filePath.length()<6)
                        continue;

                    Thread.sleep(1000);
                    String result = httpUtil.updataFile(uploadUrl, filePath);
                    if(result==null){
                        Thread.sleep(1000);
                        result = httpUtil.updataFile(uploadUrl, filePath);

                    }
                    if(result==null)
                        continue;
                    Thread.sleep(1000);
                    JSONObject json = JSONObject.parseObject(result);
                    String finalImageUrl = json.getString("data");
                    imageList.add(finalImageUrl);
                } catch (Throwable e) {
                    System.out.println("download error " + e.getMessage());
                }
                long end = System.currentTimeMillis(); // 记录结束时间
                executionTime = end - start; // 计算执行时间（单位为毫秒）
            }
            if(imageList.size()==0){
                job.setState(2);
                Job save = jobRepository.save(job);
                System.out.println("save:"+save);

            }else {
                System.out.println("图片下载完成 " + imageList.toString());
                System.out.println("程序执行时间：" + executionTime + "ms");
                job.setFinalResultImages(imageList);
                job.setState(4);
                jobRepository.save(job);
                Notice notice = new Notice();
                notice.setJobId(job.getId());
                notice.setContent("AI生成完毕");
                notice.setType(2);
                notice.setStatus(0);
                notice.setUserId(job.getUserId());
                notice.setName("AI生成完毕可点击查看");
                noticeRepository.save(notice);
            }
        } catch (Throwable e) {
            job.setState(4);
            jobRepository.save(job);

        }

    }

}
